package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;


@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService ;

    /**
     * 图片上传
     * @param multipartFile 图片文件
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {

        //判断文件是否存在
        if (multipartFile == null || multipartFile.getSize() == 0 ) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID) ;
        }

        //随机生成文件名
        String fileName = UUID.randomUUID().toString().replace("-", "");
        //获取原文件名
        String originalFilename = multipartFile.getOriginalFilename();
        //获取原文件名后缀
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //构建图片id并上传至minio
        String fileUrl = null;
        try {
            fileUrl = fileStorageService.uploadImgFile("" , fileName + postfix , multipartFile.getInputStream()) ;
            log.info("上传图片到MinIO中，fileId:{}" , fileUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }

        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUrl(fileUrl);
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setType((short)0);
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        save(wmMaterial) ;

        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 素材列表查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //检查参数
        dto.checkParam();

        //构建分页对象
        IPage ipage = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> lamQW = new LambdaQueryWrapper<>();
        //判断当前查询的列表时全部还是收藏列表
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1 ){
            lamQW.eq(WmMaterial::getIsCollection , dto.getIsCollection()) ;
        }

        //根据当前用户id查询 按照创建时间倒序
        lamQW.eq(WmMaterial::getUserId , WmThreadLocalUtil.getUser().getId()) ;
        lamQW.orderByDesc(WmMaterial::getCreatedTime) ;

        ipage = page(ipage , lamQW) ;

        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) ipage.getTotal());
        responseResult.setData(ipage.getRecords());

        return responseResult;
    }

    /**
     * 根据id删除图片素材
     * @param id
     * @return
     */
    @Override
    public ResponseResult delpicture(Integer id) {
        if (id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID) ;
        }

        WmMaterial byId = getById(id);
        if (ObjectUtils.isEmpty(byId)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        boolean remove = removeById(id);
        if (!remove){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID , "文件删除失败");
        }

        fileStorageService.delete(byId.getUrl());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏
     * @param id
     * @return
     */
    @Override
    public ResponseResult collect(Integer id) {
        if (id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID) ;
        }

        WmMaterial material = getById(id);
        if (ObjectUtils.isEmpty(material)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        material.setIsCollection((short) 1);

        updateById(material);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 取消收藏
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancelCollect(Integer id) {
        if (id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID) ;
        }

        WmMaterial material = getById(id);
        if (ObjectUtils.isEmpty(material)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        material.setIsCollection((short) 0);

        updateById(material);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
